#include "loggermanager.h"
#include <QDateTime>
#include <QDir>
#include <QCoreApplication>
#include <QFileInfo>

LoggerManager& LoggerManager::getInstance()
{
    static LoggerManager instance;
    instance.init();
    return instance;
}

void LoggerManager::init()
{
    QDir parentDir = QCoreApplication::applicationDirPath();
    // 获取 logs 目录路径
    logDirPath = parentDir.filePath("logs");
    qDebug() << "Log directory path: " << logDirPath;

    // 创建日志目录（如果不存在）
    QDir dir(logDirPath);
    if (!dir.exists())
    {
        dir.mkpath(".");
    }

    createNewLogFile();

    // 初始化 SQLite 数据库
    db = SQLiteDatabase::getInstance();

    // 将当前日志文件名记录到数据库
    logToDatabase("file", currentLogFileTimestamp);
}

void LoggerManager::createNewLogFile()
{
    // 动态生成日志文件名
    QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss");
    currentLogFilePath = logDirPath + "/" + timestamp + ".log";
    currentLogFileTimestamp = timestamp;
    qDebug() << "Current log file path: " << currentLogFilePath;

    if (logFile.isOpen())
    {
        logFile.close();
    }
    logFile.setFileName(currentLogFilePath);
    logFile.open(QIODevice::Append | QIODevice::Text);
    logStream.setDevice(&logFile);
}

void LoggerManager::checkLogFileSize()
{
    QFileInfo logFileInfo(currentLogFilePath);
    if (logFileInfo.size() > 1024 * 1024)
    {
        createNewLogFile();
        logToDatabase("file", currentLogFileTimestamp);
    }
}

void LoggerManager::logToFile(const QString& level, const QString& content)
{
    QMutexLocker locker(&logMutex);
    checkLogFileSize();
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    logStream << QString("[%1] [%2] %3").arg(timestamp, level, content) << Qt::endl;
    logStream.flush();
}

void LoggerManager::logInfo(const QString& content)
{
    logToFile("INFO", content);
    qDebug() << "[INFO]" << content;
}

void LoggerManager::logWarning(const QString& content)
{
    logToFile("WARNING", content);
    qWarning() << "[WARNING]" << content;
}

void LoggerManager::logError(const QString& content)
{
    logToFile("ERROR", content);
    qCritical() << "[ERROR]" << content;
}

void LoggerManager::logOperation(const QString& content)
{
    logToFile("OPERATION", content);
    qDebug() << "[OPERATION]" << content;  // 使用 info 级别记录 operation 日志
}

void LoggerManager::logDebug(const QString& content)
{
    logToFile("DEBUG", content);
    qDebug() << "[DEBUG]" << content;
}

void LoggerManager::logToDatabase(const QString& type, const QString& timestamp)
{
    // 查询数据库中是否已存在相同时间戳的记录
    QJsonArray result = db->read("system_logs", QString("timestamp = '%1'").arg(timestamp));

    // 如果没有找到相同的记录，才进行插入操作
    if (result.isEmpty())
    {
        QJsonObject logRecord;
        logRecord["type"] = type;
        logRecord["timestamp"] = timestamp;
        db->create("system_logs", logRecord);
    }
}

QString LoggerManager::getLogFilePath(const QString& timestamp) const
{
    return logDirPath + "/" + timestamp + ".log";
}
